package com.alibaba.dubbo.remoting.msgcodec;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.remoting.MessageDecode;
import com.alibaba.dubbo.remoting.MessageEncode;

/**
 * 编解码辅助工具
 * @author kingbo.ruan
 * 2014.09.16
 *
 */
public final class MessageCodecSupport {
	
	
	public static MessageDecode[] splitDecode(String codec){
		return splitCodec(MessageDecode.class, codec);
	}
	
	public static MessageEncode[] splitEncode(String codec){
		return splitCodec(MessageEncode.class, codec);
	}
	
	
	@SuppressWarnings("unchecked")
	static <T> T[] splitCodec(Class<T> target, String codec){
		if(codec == null || codec.isEmpty()){
			return null;
		}
		List<T> result = new ArrayList<T>();
		String[] values = codec.split("\\s*[,]+\\s*");
        for (int i = 0; i < values.length; i++) {
            String v = values[i];
            v = v.trim();
            if(v.length() > 0){
            	T t = ExtensionLoader.getExtensionLoader(target).getExtension(v);
            	result.add(t);
            }
        }
        
        if(result.isEmpty()) return null;
        return result.toArray((T[])Array.newInstance(target, result.size()));
	}
}
